﻿using UnityEditor;
using UnityEditor.AddressableAssets.Settings;
using UnityEditor.AddressableAssets.Settings.GroupSchemas;
using UnityEditor.Graphs;
using UnityEngine;

namespace KuiHuaBaoDian.GuideGraph.Editor {

    public class GuideGraphAddressables {

        private string m_GroupName;

        public GuideGraphAddressables(string groupName) {
            m_GroupName = groupName;
        }

        public virtual AddressableAssetEntry AddToGroup(Object asset, AddressableAssetSettings aaSettings) {
            var group = GetGroup(asset, aaSettings);
            var guid = GetAssetGuid(asset);
            var assetEntry = aaSettings.FindAssetEntry(guid);

            if (assetEntry == null) {
                assetEntry = aaSettings.CreateOrMoveEntry(guid, group, true);
            } else {
                aaSettings.MoveEntry(assetEntry, group, true);
            }

            return assetEntry;
        }

        protected virtual AddressableAssetGroup GetGroup(Object asset, AddressableAssetSettings aaSettings) {
            return FindOrCreateGroup(m_GroupName, aaSettings);
        }

        AddressableAssetGroup FindOrCreateGroup(string name, AddressableAssetSettings aaSettings) {
            var defaultGroup = aaSettings.DefaultGroup;
            var group = aaSettings.FindGroup(name);
            if (group == null) {
                group = aaSettings.CreateGroup(name, false, false, false, defaultGroup.Schemas);
            }
            return group;
        }

        static AddressableAssetGroup CreateNewGroup(string name, bool readOnly, AddressableAssetSettings aaSettings) {
            var group = aaSettings.CreateGroup(name, false, readOnly, true, null, typeof(BundledAssetGroupSchema), typeof(ContentUpdateGroupSchema));
            var schema = group.GetSchema<BundledAssetGroupSchema>();
            schema.BundleNaming = BundledAssetGroupSchema.BundleNamingStyle.NoHash;
            return group;
        }

        AddressableAssetEntry GetAssetEntry(Object asset, AddressableAssetSettings aaSettings) => aaSettings.FindAssetEntry(GetAssetGuid(asset));

        static string GetAssetGuid(Object asset) {
            if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(asset, out var guid, out long _))
                return guid;

            Debug.LogError("Failed to extract the asset Guid for " + asset.name, asset);
            return null;
        }
    }
}
